package middleware

import (
	"time"

	"github.com/gin-gonic/gin"
	"blockchain-api/pkg/logger"
)

// Logger 日志中间件
func Logger() gin.HandlerFunc {
	return gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		logger.WithFields(map[string]interface{}{
			"status":     param.StatusCode,
			"method":     param.Method,
			"path":       param.Path,
			"ip":         param.ClientIP,
			"user_agent": param.Request.UserAgent(),
			"latency":    param.Latency,
			"time":       param.TimeStamp.Format(time.RFC3339),
		}).Info("HTTP Request")
		
		return ""
	})
}

// Recovery 恢复中间件
func Recovery() gin.HandlerFunc {
	return gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
		logger.WithFields(map[string]interface{}{
			"error": recovered,
			"path":  c.Request.URL.Path,
			"method": c.Request.Method,
		}).Error("Panic recovered")
		
		c.JSON(500, gin.H{"error": "Internal server error"})
		c.Abort()
	})
}
